//
//  FilmTicketIndexViewController.m
//  ELife
//
//  Created by  刘奇男 on 11-5-22.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "FilmTicketIndexViewController.h"
#import "FilmTicketBookViewController.h"
#import "FilmHelpViewController.h" 
#import "FilmTicketCityViewController.h"
#import "GDataXMLNode.h"
#import "GTMBase64.h"
#import "AlertView.h"



@implementation FilmTicketIndexViewController

@synthesize roundView, cityPicker, cityNames, label;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)dealloc
{
    [super dealloc];
    
    [roundView release];
    [cityPicker release];
    [cityNames release];
    [label release];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView
{
}
*/


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    
    app = [ELifeAppDelegate App];

    
    [self.navigationItem setTitle:@"电影兑换券"];
     
    roundView.layer.cornerRadius = 8;
    roundView.layer.masksToBounds = YES;
    
    [cityPicker setDelegate:self];
    [cityPicker setDataSource:self];
    
    UIBarButtonItem *temporaryBarButtonItem = [[UIBarButtonItem alloc] init];
	temporaryBarButtonItem.title = @"返回";
	self.navigationItem.backBarButtonItem = temporaryBarButtonItem;
	[temporaryBarButtonItem release];
}

- (void)viewWillAppear:(BOOL)animated
{
    [app controllNum:0 setNavigationBar:NO animated:NO];
}


- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (IBAction) next:(id)sender
{
    if ([label.text length] == 0){
        [AlertView showAlert:@"请先选择城市"];
        return;
    }
    
    FilmTicketBookViewController *controller = [[FilmTicketBookViewController alloc] initWithNibName:@"FilmTicketBookView" bundle:nil];
    
    [controller setCity:label.text];
    
    [self.navigationController pushViewController:controller animated:YES];
    [controller release];
}

- (IBAction) help:(id)sender
{
    FilmHelpViewController *controller = [[FilmHelpViewController alloc] initWithNibName:@"FilmHelpView" bundle:nil];
    [self.navigationController pushViewController:controller animated:YES];
    [controller release];
}


-(void) request
{
    app = [ELifeAppDelegate App];
    [app showProgressDialog:@"请稍候"];
    
    //    [table setDataSource:self];
    //    [table setDelegate:self];
    
    /*10.7 查询所支持城市
     请求地址: /cinema.php
     请求参数: action  => get_city_list
     
     返回参数: 
     citys = 城市；
     city = 城市；
     
     返回格式事例: 
     <?xml version="1.0" encoding="UTF-8"?><msg><head><returncode>0</returncode><transcode>get_city_list</transcode></head><body><cities><city>上海</city><city>成都</city><city>杭州</city><city>天津</city><city>北京</city><city>呼和浩特</city><city>广州</city><city>深圳</city><city>海口</city><city>太原</city><city>武汉</city><city>重庆</city><city>福州</city><city>南京</city><city>运城</city><city>青岛</city><city>郑州</city><city>济南</city></cities></body></msg>*/
    
    NSString* host =  [[NSBundle mainBundle] localizedStringForKey:(@"BussinessHost") value:@"" table:nil];
    NSURL* url = [[NSURL alloc] initWithString:[host stringByAppendingString:@"cinema.php?"]];
    
    NSMutableDictionary *param = [[NSMutableDictionary alloc]initWithCapacity:1];
    [param setObject:@"get_city_list" forKey:@"action"];
    [param setObject:[[NSBundle mainBundle] localizedStringForKey:(@"ClientVersion") value:@"" table:nil] forKey:@"version"];
    
    NSDictionary* dic = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:url, @"iRequestFinished:", nil] forKeys:[NSArray arrayWithObjects:@"url", @"requestMethod", nil]];
    
    [[app httpRequestPoint]openUrl:dic postParam:param target:self];
    
    [param release];
}

#pragma mark -
#pragma mark 联网回调
- (void)iRequestFinished:(NSData *)response
{
    [app hideProgressDialog];
    
    GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:[GTMBase64 decodeData:response] options:0 error:nil];
    GDataXMLElement* rootElement = [doc rootElement];    
    
    GDataXMLElement* bodyElement = [[rootElement elementsForName:@"body"]objectAtIndex:0];
    
    //某个具体节点的文本内容
    GDataXMLElement* citiesElement = [[bodyElement elementsForName:@"cities"]objectAtIndex:0];
    
    NSArray *cityArr = [citiesElement children];
    
    cityNames =  [[NSMutableArray alloc] initWithCapacity:[cityArr count]];
    for (int i = 0; i<[cityArr count]; i++) {
        GDataXMLElement *element = [cityArr objectAtIndex:i];
        
        NSArray *arr = [element children];
        for (int j = 0; j<[arr count]; j++) {
            GDataXMLNode *node = [arr objectAtIndex:j];
            [cityNames addObject:[node stringValue]];
        }
    }
    
    NSLog(@"--------cityNames:--------\n%@", cityNames);
    
    [doc release];
    
    
    cityPicker.showsSelectionIndicator = YES;     
    [cityPicker setFrame:CGRectMake(0,44,0,0)];
    
    UIActionSheet *aac = [[UIActionSheet alloc] initWithTitle:@"" 
                                                     delegate:self 
                                            cancelButtonTitle:nil 
                                       destructiveButtonTitle:nil 
                                            otherButtonTitles:nil]; 
    
    
    UIToolbar* pickerDateToolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)]; 
    pickerDateToolbar.barStyle = UIBarStyleBlackOpaque; 
    [pickerDateToolbar sizeToFit]; 
    
    NSMutableArray *barItems = [[NSMutableArray alloc] init]; 
    UIBarButtonItem *flexSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil]; 
    [barItems addObject:flexSpace]; 
    
    UIBarButtonItem *doneBtn = [[UIBarButtonItem alloc] initWithTitle:@"确定" style:UIBarButtonItemStyleBordered target:self action:@selector(confirmChoseCity:)]; 
    [barItems addObject:doneBtn]; 
    [pickerDateToolbar setItems:barItems animated:YES]; 
    
    [aac addSubview:pickerDateToolbar]; 
    [aac addSubview:cityPicker]; 
    [aac showInView:self.view]; 
    [aac setBounds:CGRectMake(0,0,320, 464)]; 
    }


- (void)actionSheet:(UIActionSheet *)modalView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    // Change the navigation bar style, also make the status bar match with it
	switch (buttonIndex)
	{
	}
}

#pragma mark -
#pragma mark UIPickerViewDelegate

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
	if (pickerView == cityPicker)	// don't show selection for the custom picker
	{
		// report the selection to the UI label
//		label.text = [NSString stringWithFormat:@"%@ - %d",
//                      [cityNames objectAtIndex:[pickerView selectedRowInComponent:0]],
//                      [pickerView selectedRowInComponent:1]];
	}
}

- (IBAction) choseCity:(id)sender
{

    FilmTicketCityViewController *controller = [[FilmTicketCityViewController alloc] initWithNibName:@"FilmTicketCityView" bundle:nil];
    
    [controller setIndexController:self];

    [self.navigationController pushViewController:controller animated:YES];
    [controller release];    
}

- (IBAction) confirmChoseCity:(id)sender
{    
    
    label.text = [cityNames objectAtIndex:[cityPicker selectedRowInComponent:0]];
}

-(void) setCity:(NSString*) city
{
    label.text = city;
}


#pragma mark -
#pragma mark UIPickerViewDataSource

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
	NSString *returnStr = @"";
	
	// note: custom picker doesn't care about titles, it uses custom views
	if (pickerView == cityPicker)
	{
		returnStr = [cityNames objectAtIndex:row];
	}
	
	return returnStr;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
	return [cityNames count];
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)thePickerView {    
    return 1;
}

@end
